qui(
    function (require, exports, module) {

        Record.PlanGrid = function (options) {
            this.dao = Record.Dao;
            this.config = Record.Config;
            this.util = Record.Util;
            this.task = Record.Task;
            this.options = options || {};
        };

        Com.inherits(Record.PlanGrid, Ancestor.Grid).extend({
            doInit: function () {
                var self = this;
                var taskArr = [];
                taskArr.push(self.task.getLegoCategory("lego_category"))
                $.each(taskArr, function (index, element) {
                    EpgWeb.ajaxQueue.push(element.regName, element.options);
                })
                EpgWeb.ajaxQueue.afterLoadComplete(function () {
                    self.bindEvent();
                    self.initDateTimePicker();
                    self.initSuggest();
                    self.initGrid();
                    self.initSelect();
                    self.initDlg();
                    self.initFirstQuery();
                })
                EpgWeb.ajaxQueue.startLoad();
            },
            initFirstQuery: function () {
                $("#belong_channel_div").hide();
                try {
                    var channelId = Com.url.getParameter("channel_id");
                    if (channelId != null && !isNaN(channelId)) {
                        $("input[name='EQL_channel.id']").val(channelId);
                    } else {
                        $("#belong_channel_div").show();
                    }
                } catch (e) {
                    console.log("initFirstQuery error");
                }
                var self = this;
                self.query();
            },
            bindEvent: function () {
                var self = this;
                $("button[name=open_new_dlg_btn]").bind("click", function (event) {
                    var channelId = Com.url.getParameter("channel_id");
                    if (channelId != null && !isNaN(channelId)) {
                        Record.Util.openPlanModifyDlg(parseInt(channelId),1);
                    } else {
                        Record.Util.openPlanModifyDlg(-1);
                    }
                })

                $("button[name=query_btn]").bind("click", function (event) {
                    self.query();
                })
                $(".query-chosen-select").chosen({width: "300px"});
                $(".chosen-select").chosen({width: "300px"});

                $("select[name='EQI_recordPlan.play_type']").bind("change", function (event) {
                    if ($(event.currentTarget).val() == 1) {
                        $("#record-plan-repeat-div").show();
                    } else {
                        $("#record-plan-repeat-div").hide();
                    }
                })
            },
            initDateTimePicker: function () {
                EpgWeb.Util.bindDate("'GES_recordPlan.create_time'", "'LES_recordPlan.create_time'");
                var now = new Date();
                $('input[name="start_date"]').datepicker({
                    yearRange: '2010:C+5',
                    addSliderAccess: true,
                    minDate : now,
                    sliderAccessArgs: { touchonly: false },
                    onClose: function (selectedDate) {
                        $('input[name="stop_date"]').datepicker("option", "minDate", selectedDate);
                    }
                });
                $('input[name="stop_date"]').datepicker({
                    yearRange: '2010:C+5',
                    addSliderAccess: true,
                    sliderAccessArgs: { touchonly: false },
                    onClose: function (selectedDate) {
                        $('input[name="start_date"]').datepicker("option", "maxDate", selectedDate);
                    }
                });
                $('input[name="start_day_time"]').timepicker({
                    yearRange: '2010:C+5',
                    addSliderAccess: true,
                    minTime: now,
                    sliderAccessArgs: { touchonly: false }
                });
                $('input[name="stop_day_time"]').timepicker({
                    yearRange: '2010:C+5',
                    addSliderAccess: true,
                    sliderAccessArgs: { touchonly: false }
                });
            },

             initSuggest: function () {
                 var self = this;
                var channelSuggest = {
                    options: {
                        ajaxSettings: {
                            beforeSend: function (request) {
                                var authBase = Ancestor.Util.getAuth("/record/channel/list");
                                request.setRequestHeader('Sign', authBase.sign);
                                request.setRequestHeader("Time", authBase.clientTime);
                                request.setRequestHeader("From", authBase.from);
                                request.setRequestHeader("UserName", (auth.baseInfo.authInfo == null) ? "" : escape(auth.baseInfo.authInfo.userName).toLocaleLowerCase().replace(/%u/gi, '\\u'));
                            }
                        },
                        select: function (event, object) {
                            var obj = { "EQL_channelId": Number(object.item.id) };
                            Record.Dao.getColList({paramsObj: JSON.stringify(obj), dataMode: "simple", pageSize: 100}, function (retData) {
                                Record.Util.fillRelationColSelect(retData);
                            })
                            return true;
                        },
                        source: Record.urlConfig.getRecordChannelUrl,
                        method: "post",
                        autoFilter: false,
                        autoFocus: false,
                        multiple: false,
                        parseValue: function () {
                            var val = this.element.val(),
                                ret = []
                            return ret;
                        },
                        getParam: function (term) {
                            var jsonObj = { LIKES_channelName: $.trim(term) };
                            return { "dataMode": "simple", paramsObj: JSON.stringify(jsonObj) }
                        },
                        process: function (json) {
                            var ret = [],
                                self = this,
                                options = self.options,
                                itemData = null;
                            var data = null;
                            if (json == null) {
                                return [];
                            }
                            if (json.code === "A00000") {
                                data = json.data == null ? null : json.data;
                            }
                            if (!data) {
                                return [];
                            }
                            $.map(data.result, function (item) {
                                itemData = {};
                                itemData[options.valueKey] = item["id"];
                                itemData[options.labelKey] = item["channelName"]
                                ret.push(itemData);
                            });
                            return ret;
                        },
                        template: function (item) {
                            return item.label;
                        }
                    }
                }

                $("input[name=channel_name]").suggest(channelSuggest.options);

                var emailSuggest = {
                    options: {
                        source: Record.urlConfig.redirectUrl,
                        method: "post",
                        autoFilter: false,
                        autoFocus: false,
                        parseValue: function () {
                            var val = this.element.val(),
                                ret = []
                            return ret;
                        },
                        getParam: function (term) {
                            var requestData = {url: Record.Constant.thirdUrl_query_user, type: "get", params: {email: term}, needCookie: true};
                            return {"request": JSON.stringify(requestData), timeSign: new Date().getTime()}
                        },
                        process: function (json) {
                            var ret = [],
                                self = this,
                                options = self.options,
                                itemData = null;
                            var data = null;
                            if (json == null) {
                                return [];
                            }
                            if (json.code === "A00000") {
                                data = json.data == null ? null : json.data;
                            }
                            if (!data) {
                                return [];
                            }
                            $.map(data, function (item) {
                                itemData = {};
                                itemData[options.valueKey] = item["email"];
                                itemData[options.labelKey] = item["userName"]
                                itemData["value"] = item["userName"];
                                itemData["email"] = item["email"];
                                itemData["uid"] = item["uid"];
                                ret.push(itemData);
                            });
                            return ret;
                        },
                        template: function (item) {
                            return item.label + "(" + item.id + ")";
                        }
                    }
                }
                $("input[name=project_workers]").suggest(emailSuggest.options);

            },
            initGrid: function (options) {
                var self = this;
                self.$grid = self.options.$grid;
                var params = self.getParam();
                var gridConfig = self.getGridConfig(self.config.PLAN_DATA_LIST);
                options = $.extend(true, {
                    mtype: 'post',
                    postData: $.extend(true, {}, params)
                }, gridConfig, options);
                self.$grid.jqGrid(options);
            },
            query: function (callback) {
                var self = this;
                var $grid = self.$grid;
                var params = self.getParam();
                params.sortType = "desc";
                $grid.jqGrid('setGridParam', {
                    page: 1,
                    datatype: "json",
                    postData: params
                }).trigger('reloadGrid');
            },
            getParam: function () {
                var params = {};
                var inputArr = $('form[role="queryForm"]').find("input[role=query-text]")
                $.each(inputArr, function (i, element) {
                    if (element.value.trim().length > 0) {
                        params [$(element).attr("name")] = element.value.trim()
                    }
                })
                var selectArr = $('form[role="queryForm"]').find("select[role=query-select]")
                $.each(selectArr, function (i, element) {
                    if (element.name != "query-repeat-code") {
                        if (element.value.trim().length > 0) {
                            params [$(element).attr("name")] = element.value.trim()
                        }
                    }
                })
                if ($("select[name=query-repeat-code]").is(":visible")) {
                    var repeatCodeArr = $("select[name=query-repeat-code]").val();
                    if (repeatCodeArr != null) {
                        var repeatCodeValue = 0;
                        $.each(repeatCodeArr, function (i, codeValue) {
                            repeatCodeValue = repeatCodeValue | parseInt(codeValue);
                        })
                        params["EQL_recordPlan.repeat_code&" + repeatCodeValue] = repeatCodeValue;
                    }
                }
                params["EQI_recordPlan.status"] = 1;
                console.log("params:" + JSON.stringify(params));

                return { paramsObj: JSON.stringify(params) };
            },
            initSelect: function () {
                var resultData = Record.Dao.getDataByName("lego_category");
                var filterArr = [];
                $.each(resultData.data, function (i, element) {
                    filterArr.push({ key: element.id, val: element.name})
                })
                var selectJDom = $("select[name='EQI_col.category_id']");
                $("<option value=''>全部</option>").appendTo(selectJDom);
                $.each(filterArr, function (index, obj) {
                    $("<option>", {
                        value: obj.key,
                        html: obj.val
                    }).appendTo(selectJDom);
                });
            },
            initDlg: function () {
                var self = this;
                self.initAddFormDlg();
            },

            initAddFormDlg: function () {
                $("form[role=addForm]").dialog({
                    title: "新建计划",
                    autoOpen: false,
                    height: 640,
                    width: 840,
                    modal: true
                })
                $("button[name=add_plan_btn]").bind("click", function (event) {
                    Record.Util.sendAddRecordPlan();
                })
                $("button[name=edit_plan_btn]").bind("click", function (event) {
                    Record.Util.sendEditRecordPlan();
                })
                $("button[name=cancel_btn]").bind("click", function (event) {
                    $("form[role=addForm]").dialog("close")
                })
                $("input[name=plan_type]").bind("click", function (event) {
                    var value = $(event.currentTarget).val();
                    if (value == 1) {
                        $("#range_time_div").show();
                        $("#repeat_code_div").show();
                        $("#fragment_output_div").hide();
                    } else if (value == 2) {
                        $("#range_time_div").hide();
                        $("#repeat_code_div").hide();
                        $("#fragment_output_div").show();
                    }
                })

                $("select[name=enable]").on('change',function (event) {
                    var parentDom = $("form[role=addForm]");
                    if($(this).attr('status') && $(this).attr('status')== 1 && $(this).val()==1){
                        parentDom.find('input').each(function(i,ele){
                            $(ele).attr('disabled','disabled');

                        });
                        parentDom.find('select[name="col_name"]').attr('disabled','disabled');
                        parentDom.find(".chosen-select").prop('disabled', true).trigger("chosen:updated");
                        parentDom.find(".qui-tag-remove").each(function(i,ele){
                            $(ele).hide();
                        });
                    }else{
                        parentDom.find('input').each(function(i,ele){
                            if( $(ele).attr('name')!= 'channel_name' ){
                                $(ele).attr('disabled',false);
                            }
                        });
                        parentDom.find('select[name="col_name"]').attr('disabled',false);
                        parentDom.find(".chosen-select").prop('disabled', false).trigger("chosen:updated");
                        parentDom.find(".qui-tag-remove").each(function(i,ele){
                            $(ele).show();
                        });
                    }
                })
            }
        });

    }
);